<template>

  <div>
    <!--搜索重置部分-->
    <div style="margin: 10px 0;display: flex">


      <!--      <el-input style="width: 200px" placeholder="请输入指导老师id" suffix-icon="el-icon-message" class="ml-5" v-model="TeamGuiderId"></el-input>-->
      <el-button type="warning" @click="reset">重置</el-button>
      <div style="margin-left: 30px">
        <el-dropdown placement="top-start" size="small" @command="select">
  <span class="el-dropdown-link">
    选择比赛<i class="el-icon-arrow-down el-icon--right"></i>
  </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="competition in competitions"
                              :key="competition"
                              :command="competition">
              {{ competition }}
            </el-dropdown-item>

          </el-dropdown-menu>
        </el-dropdown>

      </div>
      <div class="block" style="margin-left: 30px">
        <span class="demonstration" style="color: #409EFF">年份 : </span>
        <el-date-picker
            v-model="tempyear"
            type="year"
            placeholder="选择年份"
            @change="timeselect"
        >
        </el-date-picker>
      </div>

    </div>

    <!--&lt;!&ndash;发布比赛&ndash;&gt;-->
    <!--<div>-->
    <!--  <el-button style="float:right" type="danger" @click="submitForm('publishForm')">发布比赛</el-button>-->
    <!--</div>-->

    <div style="margin: 10px 0">
      <!--导入 路径后期改-->
      <el-upload :headers="{Authorization:JSON.parse(localStorage.getItem('user'))}"
                 action="http://localhost:9090/Excel/read" :show-file-list="false" accept="xlsx"
                 :on-success="handleExcelImportSuccess"
                 :on-error="handleExcelImportError" style="display: inline-block">
        <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
      </el-upload>

      <!--导出-->

      <el-button type="success" @click="modleDownLoad" class="ml-5">模板下载 <i class="el-icon-bottom"></i></el-button>
      <el-button type="primary" @click="expById" class="ml-5">批量导出 <i class="el-icon-top"></i></el-button>
      <el-button type="primary" @click="expByAll" class="ml-5">导出所有 <i class="el-icon-top"></i></el-button>
      <el-button type="primary" @click="addTime" class="ml-5">一键加时 <i class="el-icon-top"></i></el-button>
      <el-button type="success" @click="selectLevel" class="ml-5">选中评级 <i class="el-alert--info"></i></el-button>
    </div>
    <el-dialog
        title="增加时间"
        :visible.sync="timedialog"
        width="30%"
        :before-close="handleClose">


      <span style="color: green">用法 :  </span>
      <span>此功能是为了给导入后
        没有设置时间的获奖名单一键添加时间</span>
      <br>
      <div style="margin-top: 30px"></div>

      <div class="block">
        <span class="demonstration">年份选择 : </span>
        <el-date-picker
            v-model="year"
            type="year"
            placeholder="选择年份"
        >
        </el-date-picker>
      </div>


      <span slot="footer" class="dialog-footer">
    <el-button @click="timedialog = false">取 消</el-button>
    <el-button type="primary" @click="inserttime">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
        title="选中评级"
        :visible.sync="leveldialog"
        width="30%"
        :before-close="handleClose">


      <span style="color: green">用法 :  </span>
      <span>导入后没有办法判断等级,需要选中后进行
      等级判断</span>
      <br>
      <div style="margin-top: 30px"></div>

      <div class="block">
        <el-select v-model="value" clearable placeholder="请选择">
          <el-option
              v-for="item in levelList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </div>


      <span slot="footer" class="dialog-footer">
    <el-button @click="leveldialog = false">取 消</el-button>
    <el-button type="primary" @click="insertSelevtLevel">确 定</el-button>
  </span>
    </el-dialog>

    <!--表单数据-->
    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="contestName" label="竞赛名称" width="140"></el-table-column>

      <el-table-column prop="projectName" label="项目名称" width="120"></el-table-column>
      <el-table-column prop="rigLevel" label="认定级别" width="120"></el-table-column>
      <el-table-column prop="performanceScore" label="业绩分值" width="120"></el-table-column>
      <!--      <el-table-column prop="organizer" label="主办单位" width="200"></el-table-column>-->
      <el-table-column prop="priceLevel" label="获奖级别"></el-table-column>
      <el-table-column prop="teamGuider" label="第一指导老师姓名"></el-table-column>
      <el-table-column prop="teamGuiderCollege" label="所在学院"></el-table-column>
      <el-table-column prop="teamGuiderPhone" label="联系电话"></el-table-column>
      <el-table-column prop="teamGuiderId" label="工号"></el-table-column>
      <el-table-column prop="cardNumber" label="工资发放工行账号"></el-table-column>
      <el-table-column prop="teamLeaderName" label="学生团队负责人姓名"></el-table-column>
      <el-table-column prop="teamLeaderId" label="学号"></el-table-column>
      <el-table-column prop="teamLeaderPhone" label="联系电话"></el-table-column>
      <el-table-column prop="teamLeaderCollege" label="所在学院"></el-table-column>
      <el-table-column prop="teamLeaderClass" label="班级"></el-table-column>
      <el-table-column prop="teamLeaderCode" label="身份证号码"></el-table-column>
      <el-table-column prop="teamLeaderCardNumber" label="学费扣费工行帐号"></el-table-column>
      <el-table-column prop="bankingDetails" label="开户行信息"></el-table-column>
      <el-table-column prop="studentBonuses" label="学生奖金比例%"></el-table-column>
      <el-table-column prop="otherStudents" label="团队其他成员名单"></el-table-column>
      <!--修改、删除操作-->
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--页码部分-->
    <!--<div style="padding: 10px 0">-->
    <div style="padding: 10px 0">
      <span class="demonstration"></span>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!--新增与修改-->
    <el-dialog title="获奖信息" :visible.sync="dialogFormVisible" width="60%">
      <el-form label-width="80px" size="small" style="display: flex">
        <div style="width: 50%">

          <el-form-item label="竞赛名称">
            <el-input v-model="form.contestName" autocomplete="off"
                      oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
          </el-form-item>
          <el-form-item label="项目名称">
            <el-input v-model="form.projectName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="主办单位">
            <el-input v-model="form.organizer" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="获奖级别">
            <el-input v-model="form.priceLevel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="第一指导老师姓名">
            <el-input v-model="form.teamGuider" autocomplete="off" style="margin-top: 20px"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="form.teamGuiderPhone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="工号" style="margin-left:-30px">
            <el-input v-model="form.teamGuiderId" autocomplete="off" style="width: 92%;margin-left: 30px"></el-input>
          </el-form-item>
          <el-form-item label="工资发放工行账号">
            <el-input v-model="form.cardNumber" autocomplete="off" style="margin-top: 20px"></el-input>
          </el-form-item>
          <el-form-item label="年份" style="margin-left:-30px">
            <el-input v-model="form.year" autocomplete="off" style="width: 92%;margin-left: 30px"></el-input>
          </el-form-item>
          <div style="display: flex">
            <el-upload :headers="{Authorization:JSON.parse(localStorage.getItem('user'))}"
                       action="http://localhost:9090/Team/submitDoc" :show-file-list="false"
                       accept=".docx,.pdf,image/*,.rar,.zip" :on-success="handleSuccess"
                       :on-error="handleError" :before-upload="handFileBefore" multiple style="display: inline-block"
                       :limit="5" :on-exceed="handleExceed" :data="dataID">
              <el-button type="primary" class="ml-5">上传附件 <i class="el-icon-bottom"></i></el-button>

            </el-upload>
            <!--          <el-form-item label="状态">-->
            <!--          <el-input v-model="form.status" autocomplete="off" disabled></el-input>-->
            <!--          </el-form-item>-->
          </div>


        </div>

        <div style="width: 50%">
          <el-form-item label="负责人姓名" label-width="100px">
            <el-input v-model="form.teamLeaderName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="负责人学号" label-width="100px">
            <el-input v-model="form.teamLeaderId" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" label-width="100px" style="margin-left: -10px">
            <el-input v-model="form.teamLeaderPhone" autocomplete="off" style="width: 97%;margin-left: 10px"></el-input>
          </el-form-item>
          <el-form-item label="班级" label-width="100px" style="margin-left: -30px">
            <el-input v-model="form.teamLeaderClass" autocomplete="off" style="margin-left:30px;width:92%;"></el-input>
          </el-form-item>
          <el-form-item label="学费扣费工行账号">
            <el-input v-model="form.teamLeaderCardNumber" autocomplete="off"
                      style="margin-top: 20px;width:94%;margin-left: 20px"></el-input>
          </el-form-item>
          <el-form-item label="开户行信息" label-width="100px">
            <el-input v-model="form.bankingDetails" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="身份证号码" label-width="100px">
            <el-input v-model="form.teamLeaderCode" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学生奖金比例%">
            <el-input v-model="form.studentBonuses" autocomplete="off"
                      style="margin-top: 20px;width:94%;margin-left: 20px"></el-input>
          </el-form-item>
          <el-form-item label="团队其他成员名称">
            <el-input v-model="form.otherStudents" autocomplete="off"
                      style="margin-top: 3px;width: 94%;margin-left: 20px"></el-input>
          </el-form-item>
        </div>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>

export default {
  name: 'AwardInfo',
  data() {

    return {
      //评级集合
      levelList: [
        {
          value: '院级',
          label: '院级'
        }, {
          value: '校级',
          label: '校级'
        }, {
          value: '省级',
          label: '省级'
        }, {
          value: '国家级',
          label: '国家级'
        },
      ],
      value: '',

      dataID: {
        id: ""
      },
      contestyear: "",
      tempyear: "",
      year: '',
      timedialog: false,
      leveldialog: false,
      //所有比赛的名字
      competitions: [],

      localStorage: window.localStorage,
      // TeamGuiderId:"",
      ContestName: "",
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      multipleSelection: [],
      tempSelect: [],
      headerBg: 'headerBg',
      form: {
        id: "",
        rigLevel: "",
        performanceScore: "",
        TeamGuiderCollege: "",
        contestName: "",
        projectName: "",
        organizer: "",
        priceLevel: "",
        teamGuider: "",
        teamGuiderPhone: "",
        teamGuiderId: "",
        cardNumber: "",
        TeamLeaderCollege: "",
        teamLeaderName: "",
        teamLeaderId: "",
        teamLeaderPhone: "",
        teamLeaderClass: "",
        teamLeaderCode: "",
        teamLeaderCardNumber: "",
        bankingDetails: "",
        studentBonuses: "",
        otherStudents: "",
        year: "",


      },
      dialogFormVisible: false,
      uploadingFiles: [],//上传文件的列表
    }

  },
  created() {
    this.load()
  },
  methods: {
    //模板下载功能·
    modleDownLoad() {
      window.location.href = 'http://localhost:9090/admin/getModle';
    },



    selectLevel() {
      this.leveldialog = true;
    },
    timeselect() {
      const date = this.tempyear
      const dateObject = new Date(date);
      this.contestyear = dateObject.getFullYear();
      this.request.get("/admin/AllContest", {params: {year: this.contestyear}}).then(res => {
        console.log(res)
        this.competitions = res;
      })
      this.load();


    },
    inserttime() {
      //获取那个时间得年
      const date = this.year
      const dateObject = new Date(date);
      const year = dateObject.getFullYear();
      const data = {year}
      console.log(data)
      this.request.post("/admin/inserttime", data).then(res => {
        this.$message.success("添加成功")
        this.timedialog = false;
      }).catch(error => {
        this.$message.error("添加失败")
      })
    },
    select(command) {
      console.log(command)
      this.ContestName = command
      this.load()

    },


    //Excel表格上传错误返回
    handleExcelImportError() {
      this.$message.error("请检查传入文件是否有误!")
    },
    load() {


      this.request.get("/admin/awardInfo/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          ContestName: this.ContestName,
          // TeamGuiderId: this.TeamGuiderId,
          Year: this.contestyear
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total

      })


    },
    handleClose() {
      this.timedialog = false;
      this.leveldialog = false;
    },
    //插入选中评级
    insertSelevtLevel() {
      //获取到这个集合里的id,然后对这个id进行
      let ids = this.multipleSelection.map(v => v.id)
      //再获取这个级别
      let value = this.value;
      //一起发送给后端
      let data = {
        ids: ids,
        level: value
      };
      this.request.post("/admin/selectLevel",data).then(res=>{
        if (res.code==='200'){
          this.$message.success("修改成功")
          this.leveldialog = false;
          this.multipleSelection = [];
          this.load();
        }else {
          this.$message.error(res.msg)
          console.log(res)
        }

      }).catch(error=>{
        this.$message.error("修改失败")
      })


    },
    save() {


      this.request.post("/admin/saveaward", this.form).then(res => {
        if (res) {
          console.log(res)
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          console.log(res)
          this.$message.error("保存失败")
        }
      }).catch(error => {
        console.error(error.response)
        this.$message.error("保存失败")
      })
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    handleEdit(row) {
      this.form = row
      this.dialogFormVisible = true
      this.dataID.id = this.form.id


    },
    del(id) {
      this.request.delete("/admin/awardinfo/" + id).then(res => {
        if (res) {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val

    },

    reset() {
      this.ContestName = ""
      this.TeamGuiderId = ""
      this.tempyear = ""
      this.timeselect()

    },
    handleSizeChange(pageSize) {


      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()


    },
    expById() {
      const d = new Date();
      const year = d.getFullYear();
      const month = d.getMonth() + 1;
      const date = d.getDate();
      const H = d.getHours();
      const m = d.getMinutes();
      const s = d.getSeconds();

      let ids = this.multipleSelection.map(v => v.id) // [{}, {}, {}] => [1,2,3]
      const token = localStorage.getItem('user');
      const xhr = new XMLHttpRequest();
      xhr.open('GET', `http://localhost:9090/Excel/writeById?data=${ids}`);
      xhr.setRequestHeader('Authorization', token);
      xhr.responseType = 'blob';
      xhr.onload = function () {
        const url = window.URL.createObjectURL(xhr.response);
        const a = document.createElement('a');
        a.href = url;
        a.download = (year * 10000000000 + month * 100000000 + date * 1000000 + H * 10000 + m * 100 + s) + '获奖数据' + '.xlsx';
        a.click();
        window.URL.revokeObjectURL(url);
      };
      xhr.send();


    },
    expByAll() {
      const d = new Date();
      const year = d.getFullYear();
      const month = d.getMonth() + 1;
      const date = d.getDate();
      const H = d.getHours();
      const m = d.getMinutes();
      const s = d.getSeconds();

      let name = this.ContestName
      if (!name) {
        name = "无"
        console.log(name)
      }
      // const newName = encodeURIComponent(name)
      const token = localStorage.getItem('user');
      const xhr = new XMLHttpRequest();
      xhr.open('GET', `http://localhost:9090/Excel/writeall?contest=${name}`);
      xhr.setRequestHeader('Authorization', token);
      xhr.responseType = 'blob';
      xhr.onload = function () {
        const url = window.URL.createObjectURL(xhr.response);
        const a = document.createElement('a');
        a.href = url;
        a.download = (year * 10000000000 + month * 100000000 + date * 1000000 + H * 10000 + m * 100 + s) + '获奖数据' + '.xlsx';
        ;
        a.click();
        window.URL.revokeObjectURL(url);
      };
      xhr.send();


    },
    handleExcelImportSuccess() {
      this.$message.success("导入成功")
      this.load()

    },
    addTime() {
      this.timedialog = true
    },

    //文件上传
    handleSuccess() {
      this.$message.success("成功")
      this.dialogFormVisible = false;
    },

    handFileBefore(file) {
      if (!this.handBefore(file)) {
        return false;
      }
      this.uploadingFiles.push(file);
      return true;// 将文件加入正在上传列表
    },

    handBefore(file) {
      const acceptfile = ['docx', 'pdf', 'png', 'jpg', 'rar', 'zip']
      const fileExtension = file.name.split('.').pop().toLowerCase();
      if (!acceptfile.includes(fileExtension)) {
        this.$message.error("请上传符合格式得文件!")
        return false;
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('文件大小不能超过 5MB');
        return false;
      }

      return true;
    },
    handleError() {
      this.$message.error("系统错误")
    },
    handleExceed(files) {
      this.$message.warning("文件选择不能超过5个!")
    }


  }
}
</script>


<style>
.headerBg {
  background: #eee !important;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.selected-item {
  background-color: #e0f0ff; /* 改变选中项的背景颜色 */
}
</style>


